package com.huanxing.cloud.shop.controller.app;

import com.huanxing.cloud.common.core.constant.MallCommonConstants;
import com.huanxing.cloud.common.core.constant.SecurityConstants;
import com.huanxing.cloud.common.core.enums.ClientTypeEnum;
import com.huanxing.cloud.common.core.util.Result;
import com.huanxing.cloud.common.core.util.ResultOps;
import com.huanxing.cloud.common.myabtis.tenant.HxTenantContextHolder;
import com.huanxing.cloud.common.security.handler.HxBusinessException;
import com.huanxing.cloud.miniapp.api.entity.WxApp;
import com.huanxing.cloud.miniapp.api.feign.RemoteWxAppService;
import com.huanxing.cloud.shop.api.entity.MobileTheme;
import com.huanxing.cloud.shop.service.IMobileThemeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 商城移动端主题
 *
 * @author lijx
 * @since 2022/3/17 10:55
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/app/mobile-theme")
@Tag(description = "appMobileTheme", name = "商城移动端主题-API")
public class AppMobileThemeController {

	private final IMobileThemeService mobileThemeService;

	private final RemoteWxAppService remoteWxAppService;

	@Operation(summary = "获取商城移动端主题")
	@GetMapping
	public Result<MobileTheme> getMobileTheme(HttpServletRequest request) {

		String clientType = request.getHeader(MallCommonConstants.HEADER_CLIENT_TYPE);
		if (clientType.equals(ClientTypeEnum.WX_MA.getCode())) {
			String appId = request.getHeader(MallCommonConstants.HEADER_APP_ID);
			WxApp wxApp = ResultOps.of(remoteWxAppService.getById(appId, SecurityConstants.SOURCE_IN))
				.getData()
				.orElseThrow(() -> new HxBusinessException("request failed"));
			HxTenantContextHolder.setTenantId(wxApp.getTenantId());
		}
		else {
			String tenantId = request.getHeader(MallCommonConstants.HEADER_TENANT_ID);
			if (!StringUtils.hasText(tenantId)) {
				return Result.fail("租户id为空");
			}
			HxTenantContextHolder.setTenantId(tenantId);
		}

		return Result.success(mobileThemeService.getMobileTheme(HxTenantContextHolder.getTenantId()));
	}

}
